package org.clevernote.main;

import org.clevernote.foundations.Authentication;
import org.clevernote.foundations.CmdParser;
import org.clevernote.foundations.StringConstants;
import org.clevernote.foundations.cmd.Cmd;

import ui.cmdline.parser.CommandLineArguments;
import ui.cmdline.parser.ParserException;

import com.evernote.edam.error.EDAMSystemException;
import com.evernote.edam.error.EDAMUserException;
import com.facebook.thrift.TException;

public class CmdRunner {

	public static void executeCmd(String[] args, Cmd cmd)
			throws ParserException, TException, EDAMUserException,
			EDAMSystemException {

		CmdParser parser = new CmdParser(cmd.getName());
		CommandLineArguments cmdline = parser.parse(args);

		if ( cmdline == null) {
			System.out.println("ERROR: can not parse cmdline " + args.toString());
			return ;
		}
		
		Authentication auth = Authentication.authenticate(cmdline.getString(
				StringConstants.USERNAME, null), cmdline.getString(
				StringConstants.PASSWORD, null));

	
		if ( auth == null) {
			System.out.println("ERROR: can not authenticate");
		}
		
		cmd.run(cmdline, auth);
	}

	public static void main(String args[]) {

		try {

			String cmdName = getCmdName(args);
			String cmdArgs[] = getCmdArgs(args);

			if (cmdName == null) {
				System.out.println("Invalid cmdline: " + args.toString());
				return;
			}

			Cmd cmd = createCmd(args[0]);

			if (cmd == null) {
				System.out.println("Unrecognized cmd: " + cmdName);
			}

			CmdRunner.executeCmd(cmdArgs, cmd);

		} catch (ParserException e) {
			e.printStackTrace();
		} catch (TException e) {
			e.printStackTrace();
		} catch (EDAMUserException e) {
			e.printStackTrace();
		} catch (EDAMSystemException e) {
			e.printStackTrace();
		}

	}

	/**
	 * Return all parameters past the first
	 * 
	 * @param _args
	 * @return
	 */
	private static String[] getCmdArgs(String[] _args) {
		if (_args == null)
			return null;

		int alen = _args.length;

		if (alen < 2)
			return null;

		String[] cmdArgs = new String[alen - 1];

		System.arraycopy(_args, 1, cmdArgs, 0, alen - 1);

		return cmdArgs;
	}

	/**
	 * Return the cmd name, which is the first element in the arg string
	 * 
	 * @param _args
	 * @return
	 */
	private static String getCmdName(String[] _args) {
		return _args[0];
	}

	private static Cmd createCmd(String _cmdName) throws ParserException {
		assert (_cmdName != null);

		_cmdName = _cmdName.trim().toLowerCase();

		if (_cmdName.equals(StringConstants.CMD_LOGIN)) {
			return new CmdLogin();
		} else if (_cmdName.equals(StringConstants.CMD_LIST_NOTEBOOKS)) {
			return new CmdListNotebooks();
		}

		return null;
	}

}
